package com.tiantian.quanminxiu.dialog;

import android.annotation.TargetApi;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.jakewharton.rxbinding.view.RxView;
import com.shenglian.utils.cache.FileCache;
import com.shenglian.utils.utils.CommonUtils;
import com.shenglian.utils.utils.ProviderPathUtils;
import com.tiantian.quanminxiu.R;
import com.tiantian.quanminxiu.api.uploadService;
import com.tiantian.quanminxiu.utils.APPUtils;
import com.tiantian.quanminxiu.utils.ActivityBase;
import com.tiantian.quanminxiu.utils.CommonEnum;
import com.tiantian.quanminxiu.utils.Constants;
import com.tiantian.quanminxiu.utils.PhotoUtils;
import com.tiantian.quanminxiu.utils.UserData;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

public class Dialog_UploadingPhoto extends ActivityBase {

    //region 初始化数据
    public static final int REQUEST_CODE_CROP = 0x11;
    private String imageCacheDir = new FileCache(thisContext).getCacheDir() + "image/";
    private File cacheFile;
    private File cameraFile;
    private String localImagePath = "";
    private String key = "";                 //key 是上传参数名称
    private String url = "";                 //url网络地址
    private int id;                          //id 是上传参数id
    //endregion

    //region onCreate
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dialog_upload_photo);
        Init();

        key = getIntent().getStringExtra("key");
        id = getIntent().getIntExtra(key, -1);
        url = getIntent().getStringExtra("url");
        RxView.clicks(findViewById(R.id.relMain)).map(View -> findViewById(R.id.relMain)).subscribe(OC_Button);
        RxView.clicks(findViewById(R.id.txtClose)).throttleFirst(2000, TimeUnit.MILLISECONDS).map(View->findViewById(R.id.txtClose)).subscribe(OC_Button);
        RxView.clicks(findViewById(R.id.txtAddCameraBtn)).map(View->findViewById(R.id.txtAddCameraBtn)).subscribe(OC_Camera_Uploading);
        RxView.clicks(findViewById(R.id.txtAddPhotoBtn)).map(View -> findViewById(R.id.txtAddPhotoBtn)).subscribe(OC_Photo_Uploading);
    }
    //endregion

    //region 点击相机 OC_Camera_Uploading
    private Action1<View> OC_Camera_Uploading = v->{
        new File(imageCacheDir).mkdirs();
        cameraFile = getCacheFile(new File(imageCacheDir), "output_image.jpg");
        APPUtils.SystemCamera_To(thisActivity, cameraFile);
    };
    //endregion

    //region 点击图册 OC_Photo_Uploading
    private Action1<View> OC_Photo_Uploading = v->{
        new File(imageCacheDir).mkdirs();
        APPUtils.SystemPhoto_To(thisActivity);
    };
    //endregion

    //region 关闭窗口 OC_Button
    private Action1<View> OC_Button = v->{
        intent = new Intent();
        switch (v.getId()) {
            case R.id.relMain:
                setResult(RESULT_OK, intent);
                break;
            default:
                setResult(RESULT_CANCELED, intent);
                break;
        }
        finish();
    };
    //endregion

    @Override
    public void InitView() {

    }

    @Override
    public void PageInit() {

    }

    //region region onActivityResult
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case CommonEnum.RequestCode.System_Photo:
                case CommonEnum.RequestCode.System_Photo_KITKAT:
                    if (intent == null) {
                        CommonUtils.showToask(thisContext, "return intent is null");
                        return;
                    }
                    // 判断手机系统版本号
                    if (Build.VERSION.SDK_INT >= 19) {
                        // 4.4及以上系统使用这个方法处理图片
                        handleImageOnKitKat(intent);
                    } else {
                        // 4.4以下系统使用这个方法处理图片
                        handleImageBeforeKitKat(intent);
                    }
                    break;
                case CommonEnum.RequestCode.System_Camera:
//                    Log.i("request","---"+fileName);filename是照相图片地址
                    startPhotoZoomA(cameraFile, 750, 750);
                    break;
                case REQUEST_CODE_CROP:
                    F_UploadingWeb(localImagePath);
            }
        }
    }
    //endregion

    //region 剪裁图片 startPhotoZoomA(File file, int outputX, int outputY)
    private void startPhotoZoomA(File file, int outputX, int outputY)
    {
        // Log.i("TAG", getImageContentUri(this, file) + "裁剪照片的真实地址");
        try
        {
            if (file.exists())
            {
                if (file.length()<50*1024)
                {
                    CommonUtils.showToask(thisContext,"图片太小，请重新上传..");
                }else if(file.length()<200*1024){
                    F_UploadingWeb(file.getPath());
                }else {
                    if (cacheFile != null)
                    {
                        cacheFile.delete();
                    }

                    localImagePath = imageCacheDir + "picture_" + System.currentTimeMillis() + ".png";

                    cacheFile = (new File(localImagePath));

                    Intent intent = new Intent("com.android.camera.action.CROP");
                    // 自己使用Content Uri替换File Uri
                    intent.setDataAndType(APPUtils.getImageContentUri(this, file), "image/*");
                    intent.putExtra("crop", "true");
                    intent.putExtra("aspectX", outputX);
                    intent.putExtra("aspectY", outputY);
                    intent.putExtra("outputX", outputX);
                    intent.putExtra("outputY", outputY);
                    intent.putExtra("scale", true);
                    intent.putExtra("return-data", false);
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(cacheFile));// 定义输出的FileUri
                    intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
                    intent.putExtra("noFaceDetection", true);
                    startActivityForResult(intent, REQUEST_CODE_CROP);
                }
            }
        }
        catch (ActivityNotFoundException e)
        {
            String errorMessage = "Your device doesn't support the crop action!";
            Toast.makeText(this, errorMessage, Toast.LENGTH_LONG).show();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
    //endregion

    //region handleImageOnKitKat
    @TargetApi(19)
    private void handleImageOnKitKat(Intent data)
    {
        Uri uri = data.getData();
        String imagePath = ProviderPathUtils.getPath(thisActivity, uri);
        // displayImage(imagePath); // 根据图片路径显示图片
        // Log.i("TAG", "file://" + imagePath + "选择图片的URI" + uri);
        startPhotoZoomA(new File(imagePath), 750, 750);
    }

    private void handleImageBeforeKitKat(Intent data)
    {
        Uri uri = data.getData();
        String imagePath = ProviderPathUtils.getPath(thisActivity, uri);
        // displayImage(imagePath);
        // Log.i("TAG", "file://" + imagePath + "选择图片的URI" + uri);
        startPhotoZoomA(new File(imagePath), 750, 750);
    }
    //endregion

    //region 上传图片 F_UploadingWeb(final String path)
    private void F_UploadingWeb(final String path) {
        uploadService service = uploadService.Factory.create();
        File file = new File(path);
        Log.e("path",path+":"+file.exists());
        RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        MultipartBody.Part body = MultipartBody.Part.createFormData("Filedata", file.getName(), requestFile);

        HashMap<String,Object> map = new HashMap<String,Object>();
        map.put("mid",UserData.Current.mid);
        map.put("sign", UserData.Current.sign);
        map.put("app_t", Constants.APP_TYPE);
        Loading_Open();
        service.uploadphoto(map,body)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.newThread())
                .finallyDo(()->{
                    Loading_Close();
                })
                .subscribe(str -> {
                    try {
                        Log.e("uploadingphoto", str.string());
                        UserData.Reload.Fragment_Mine = true;
                        UserData.Reload.Activity_EditInfo = true;
                        CommonUtils.showToask(this.getContext(),"图片上传成功");
                        finish();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }, throwable -> {
                    Log.e("uploadingphoto", throwable.getMessage());
                    CommonUtils.showToask(this.getContext(), throwable.getMessage());
                });

    }
    //endregion

    //region 创建文件 getCacheFile(File parent, String child)
    private File getCacheFile(File parent, String child)
    {
        // 创建File对象，用于存储拍照后的图片
        File file = new File(parent, child);

        if (file.exists())
        {
            file.delete();
        }
        try
        {
            file.createNewFile();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        return file;
    }
    //endregion

    //region onDestroy
    @Override
    protected void onDestroy()
    {
        super.onDestroy();
        if (cameraFile != null)
        {
            cameraFile.delete();
        }
    }
    //endregion

}